package com.dahuyou.tryy.too.simulate.interpreter.parse.clazz.clazzfile;

import com.dahuyou.tryy.too.simulate.interpreter.parse.clazz.clazzfile.attributeinfo.AttributeInfo;
import com.dahuyou.tryy.too.simulate.interpreter.parse.clazz.clazzfile.attributeinfo.impl.CodeAttribute;
import com.dahuyou.tryy.too.simulate.interpreter.parse.clazz.clazzfile.attributeinfo.impl.ConstantValueAttribute;
import com.dahuyou.tryy.too.simulate.interpreter.parse.clazz.clazzfile.constantpool.ConstantPool;

public class MemberInfo {

    private ConstantPool constantPool;
    private int accessFlags;
    private int nameIdx;
    private int descriptorIdx;
    private AttributeInfo[] attributes;

    private String name;

    private MemberInfo(ClassReader reader, ConstantPool constantPool) { this.constantPool = constantPool;
//        this.accessFlags = reader.readUint16();
        this.accessFlags = reader.readU2();
//        this.nameIdx = reader.readUint16();
        this.nameIdx = reader.readU2();
//        this.descriptorIdx = reader.readUint16();
        this.descriptorIdx = reader.readU2();
        this.attributes = AttributeInfo.readAttributes(reader, constantPool);
        this.name = this.constantPool.getUTF8(this.nameIdx);
    }

    static MemberInfo[] readMembers(ClassReader reader, ConstantPool constantPool) {
//        int fieldCount = reader.readUint16();
        int fieldCount = reader.readU2();
        MemberInfo[] fields = new MemberInfo[fieldCount];
        for (int i = 0; i < fieldCount; i++) {
            fields[i] = new MemberInfo(reader, constantPool);
        }
        return fields;
    }

    public int accessFlags() {
        return this.accessFlags;
    }

    public String name() {
        return this.constantPool.getUTF8(this.nameIdx);
    }

    public String descriptor() {
        return this.constantPool.getUTF8(this.descriptorIdx);
    }

    public CodeAttribute codeAttribute() {
        for (AttributeInfo attrInfo : attributes) {
            if (attrInfo instanceof CodeAttribute) return (CodeAttribute) attrInfo;
        }
        return null;
    }

    public ConstantValueAttribute ConstantValueAttribute() {
        for (AttributeInfo attrInfo : attributes) {
            if (attrInfo instanceof ConstantValueAttribute) return (ConstantValueAttribute) attrInfo;
        }
        return null;
    }

}
